<template>
  <v-form ref="formRef">
    <v-container max-width="96%">
      <v-row class="mt-1">
        <v-col
            cols="12"
            md="12"
        >
          <v-text-field
              label="资源路径"
              hint="资源路径"
              v-model="form.inputSrc"
              variant="outlined"
              clearable
              auto-grow
              :rules="[v => !!v || '资源路径不能为空！']"
              required
              append-inner-icon="mdi-file-arrow-up-down"
              @click:append-inner="fileTreeClick"
          >
          </v-text-field>
        </v-col>
        <v-col cols="12" md="6">
          <v-select
              v-model="form.source"
              :items="sourceList"
              label="来源"
              variant="outlined"
              placeholder="来源"
              hint="来源"
          ></v-select>
        </v-col>
        <v-col cols="12" md="6">
          <v-select
              v-model="form.team"
              :items="teamList"
              label="小组"
              variant="outlined"
              placeholder="小组"
              hint="小组"
          ></v-select>
        </v-col>
        <v-col cols="12" md="6">
          <v-select
              v-model="form.season"
              :items="seasonList"
              label="季"
              variant="outlined"
              placeholder="无法识别时可指定季"
              hint="无法识别时可指定季"
          ></v-select>
        </v-col>
        <v-col cols="12" md="6">
          <v-text-field
              v-model="form.episode"
              label="集"
              variant="outlined"
              placeholder="具体集数"
              hint="具体集数，例如1"
          ></v-text-field>
        </v-col>
<!--        <v-col cols="12" md="12">-->
<!--          <v-text-field-->
<!--              v-model="form.sePlaceholder"-->
<!--              label="季定位"-->
<!--              variant="outlined"-->
<!--              placeholder="使用{se}定位文件中的季数辅助识别"-->
<!--              hint="无法识别时可指定季"-->
<!--          ></v-text-field>-->
<!--        </v-col>-->
        <v-col cols="12" md="12">
          <v-text-field
              v-model="form.epPlaceholder"
              label="集数定位"
              variant="outlined"
              placeholder="使用{ep}定位文件中的集数辅助识别"
              hint="指定集"
          ></v-text-field>
        </v-col>
        <v-col
            cols="12"
            md="4"
        >
          <v-select
              v-model="form.mediaType"
              :items="mediaTypeList"
              label="类型"
              variant="outlined"
              placeholder="文件的媒体类型"
              hint="文件的媒体类型"
              required
              :rules="[v => !!v || '媒体类型不能为空！']"
          ></v-select>
        </v-col>
        <v-col
            cols="12"
            md="8"
        >
          <v-text-field
              label="媒体"
              hint="请点击搜索按钮进行进行搜索"
              :placeholder="'请点击搜索按钮进行进行搜索'"
              v-model="form.id"
              variant="outlined"
              clearable
              auto-grow
              append-inner-icon="mdi-magnify"
              @click:append-inner="searchDialogShow"
              :rules="[v => !!v || '媒体不能为空！']"
              required
          ></v-text-field>
        </v-col>
        <template v-if="publishHelperInfo">
          <v-col cols="12" md="12">
            <v-text-field
                label="文件名"
                v-model="publishHelperInfo.folderName"
                variant="outlined"
                clearable
                auto-grow
            ></v-text-field>
          </v-col>
          <v-col cols="12" md="12">
            <v-text-field
                label="主标题"
                v-model="publishHelperInfo.mainTitle"
                variant="outlined"
                clearable
                auto-grow
            ></v-text-field>
          </v-col>
          <v-col cols="12" md="12">
            <v-text-field
                label="副标题"
                v-model="publishHelperInfo.subTitle"
                variant="outlined"
                clearable
                auto-grow
            ></v-text-field>
          </v-col>
          <v-col cols="12" md="12">
            <v-textarea
                v-model="publishHelperInfo.intro"
                label="简介"
                variant="outlined"
            ></v-textarea>
          </v-col>
          <v-col cols="12" md="12">
            <v-textarea
                v-model="publishHelperInfo.inform"
                label="媒体信息"
                variant="outlined"
            ></v-textarea>
          </v-col>
        </template>
        <v-col cols="12" md="12">
          <div class="d-flex flex-column">
            <v-btn
                class="mt-4"
                color="success"
                block
                @click="submit"
                :loading="loading"
            >
              获取数据
            </v-btn>
            <v-btn
                class="mt-4"
                color="success"
                block
                :disabled="!publishHelperInfo"
                @click="confirmPublishInfoClick"
                :loading="confirmLoading"
            >
              确认发布数据
            </v-btn>
            <v-btn
                class="mt-4"
                color="info"
                block
                :disabled="!publishHelperInfo"
                :block
                @click="openAutoFeed"
            >
              获取auto feed链接
            </v-btn>
          </div>
        </v-col>
      </v-row>
    </v-container>
  </v-form>
  <v-dialog max-width="600" v-model="searchShow">
    <template v-slot:default="{ isActive }">
      <v-card id="log-textarea-card">
        <v-card-item>
          <v-card-subtitle>
            <v-text-field
                v-model="keyword"
                variant="outlined"
                hide-details="auto"
                @keyup.enter="getTvMediaList"
                clearable
            ></v-text-field>
          </v-card-subtitle>
        </v-card-item>
        <v-card-text v-show="tvMovieList && tvMovieList.length">
          <v-card v-for="tvMedia in tvMovieList" style="cursor: pointer" @click="tvMediaClick(tvMedia)">
            <template v-slot:prepend>
              <v-img rounded="lg" width="50" height="75" :src="'https://image.tmdb.org/t/p/w500' + tvMedia.posterPath"></v-img>
            </template>
            <template v-slot:title>
              <span class="text-subtitle-2">
                {{tvMedia.title}}
                <span v-if="tvMedia.year">
                  （{{tvMedia.year}}）
                </span>
              </span>
            </template>
            <template v-slot:subtitle>
              <p class="text-caption text-overflow">
                {{tvMedia.overview}}
              </p>
            </template>
          </v-card>
        </v-card-text>
      </v-card>
    </template>
  </v-dialog>
  <v-dialog width="600px" v-model="fileTreeShow">
    <v-card
        prepend-icon="mdi-update"
        title="选择文件/文件夹"
    >
      <file-tree v-model:selected="form.inputSrc"></file-tree>
      <template v-slot:actions>
        <v-btn
            color="warning"
            text="取消"
            @click="fileTreeShow = false"
        ></v-btn>
        <v-btn
            color="success"
            text="确定"
            @click="fileTreeShow = false"
        ></v-btn>
      </template>
    </v-card>
  </v-dialog>
</template>

<script setup>
import {onMounted, ref} from "vue";
import {toast} from "vue3-toastify";
import {
  autoFeedUrl,
  confirmPublishInfo,
  getMediaType,
  getPublishHelperInfo,
  getSource,
  getTeam,
  getTvMedia
} from "../api/mediaApi.js";
import FileTree from "../components/FileTree.vue";

const form = ref({
  id: null,
  inputSrc: null,
  intro: '',
  outputSrc: null,
  mediaType: '',
  existType: 'cover',
  orgStruct: null,
  source: '',
  team: '',
  season: null,
  episode: null,
  folderName: '',
  mainTitle: '',
  subTitle: '',
  inform: '',
  sePlaceholder: '',
  epPlaceholder: '',
  originalTitle: ''
});

const mediaTypeList = ref([]);
const getMediaTypeList = () => {
  getMediaType().then(res => {
    if (res.code === 200) {
      mediaTypeList.value = res.data;
    } else {
      toast.error(res.msg);
    }
  })
};
getMediaTypeList();

const sourceList = ref([]);
const getSourceList = () => {
  getSource().then(res => {
    if (res.code) {
      sourceList.value = res.data;
    } else {
      toast.error(res.msg);
    }
  })
}
getSourceList();

const teamList = ref([]);
const getTeamList = () => {
  getTeam().then(res => {
    if (res.code) {
      teamList.value = res.data;
    } else {
      toast.error(res.msg);
    }
  })
}
getTeamList();

const seasonList = ref([{title: "", value: null}]);
for (let i = 0; i < 10000; i++) {
  seasonList.value.push({title: `第${i}季`, value: i});
}

const searchShow = ref(false);
const searchDialogShow = () => {
  searchShow.value = true;
}

const keyword = ref('');
const tvMovieList = ref([]);
const getTvMediaList = () => {
  if (keyword.value.trim() === '') return;
  getTvMedia(keyword.value).then(res => {
    if (res.code === 200) {
      tvMovieList.value = res.data;
    } else {
      toast.error(res.msg);
    }
  })
}

const publishHelperInfo = ref(null);
const tvMediaClick = (tvMedia) => {
  searchShow.value = false;
  form.value.id = tvMedia.id;
  form.value.mediaType = tvMedia.mediaType;
  form.value.originalTitle = tvMedia.originalTitle;
}

const formRef = ref();
const loading = ref(false);
const submit = async () => {
  const { valid } = await formRef.value.validate()
  if (!valid) return;
  loading.value = true;
  getPublishHelperInfo({
    id: form.value.id,
    mediaType: form.value.mediaType,
    filePath: form.value.inputSrc,
    originalTitle: form.value.originalTitle,
    season: form.value.season,
    episode: form.value.episode,
    source: form.value.source,
    team: form.value.team,
    sePlaceholder: form.value.sePlaceholder,
    epPlaceholder: form.value.epPlaceholder,
    host: location.protocol + '//' + location.host
  }).then(res => {
    loading.value = false;
    if (res.code === 200) {
      publishHelperInfo.value = res.data;
      searchShow.value = false;
    } else {
      toast.error(res.msg);
    }
  }).catch(e => {
    loading.value = false;
    console.log(e);
  });
}

const confirmLoading = ref(false);
const confirmPublishInfoClick = () => {
  if (!publishHelperInfo.value) {
    toast.info('请先获取数据');
    return;
  }
  confirmLoading.value = true;
  confirmPublishInfo(publishHelperInfo.value).then(res => {
    if (res.code === 200) {
      toast.success(res.msg);
      publishHelperInfo.value = res.data;
    } else {
      toast.error(res.msg);
    }
    confirmLoading.value = false;
  }).catch(e => {
    confirmLoading.value = false;
    console.log(e);
  });
}

const openAutoFeed = () => {
  if (publishHelperInfo.value.torrentState === null) {
    toast.info('请先确认信息');
    return;
  }
  autoFeedUrl(publishHelperInfo.value.id).then(res => {
    if (res.code === 200) {
      window.open(publishHelperInfo.value.autoFeedUrl, '_blank')
    } else {
      toast.info(res.msg);
    }
  })

}

const fileTreeShow = ref(false);
const fileTreeClick = () => {
  fileTreeShow.value = true;
}

const wsInit = (ws) => {
  ws.onopen = () => {
    this.ws.send("open：", ws.readyState);
  }
  ws.onclose = () => {
    console.log("close：", ws.readyState);
  }
  ws.onmessage = (message) => {
    console.log("message：", message, ws.readyState);
  }
  ws.onerror = (error) => {
    console.log("error：", error, ws.readyState);
  }

}

const ws = ref(null);
onMounted(() => {
  ws.value = new WebSocket(`ws://${location.host}/api/websocket/test`);
  wsInit(ws.value);
})
</script>

<style scoped>
.text-overflow {
  display: -webkit-box;
  line-clamp: 3;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3;
  overflow: hidden;
  white-space: break-spaces;
}
</style>

<style>
</style>